package site.wetsion.galio.sdk.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.security.SecureRandom;
import java.util.regex.Pattern;

/**
 * 基于Spring security 的BcryPasswordEncoder
 *
 * @author weixin
 * @version 1.0
 * @CLassName GalioBcryPasswordEncoder
 * @date 2019/3/12 6:10 PM
 */
public class GalioBcryPasswordEncoder {

    private Pattern BCRYPT_PATTERN = Pattern
            .compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}");
    private final Log logger = LogFactory.getLog(getClass());

    private final int strength;

    private final SecureRandom random;

    public GalioBcryPasswordEncoder() {
        this(-1);
    }

    /**
     * @param strength the log rounds to use, between 4 and 31
     */
    public GalioBcryPasswordEncoder(int strength) {
        this(strength, null);
    }

    /**
     * @param strength the log rounds to use, between 4 and 31
     * @param random the secure random instance to use
     *
     */
    public GalioBcryPasswordEncoder(int strength, SecureRandom random) {
        if (strength != -1 && (strength < GalioBCrypt.MIN_LOG_ROUNDS || strength > GalioBCrypt.MAX_LOG_ROUNDS)) {
            throw new IllegalArgumentException("Bad strength");
        }
        this.strength = strength;
        this.random = random;
    }

    public String encode(CharSequence rawPassword) {
        String salt;
        if (strength > 0) {
            if (random != null) {
                salt = GalioBCrypt.gensalt(strength, random);
            }
            else {
                salt = GalioBCrypt.gensalt(strength);
            }
        }
        else {
            salt = GalioBCrypt.gensalt();
        }
        return GalioBCrypt.hashpw(rawPassword.toString(), salt);
    }

    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if (encodedPassword == null || encodedPassword.length() == 0) {
            logger.warn("Empty encoded password");
            return false;
        }

        if (!BCRYPT_PATTERN.matcher(encodedPassword).matches()) {
            logger.warn("Encoded password does not look like BCrypt");
            return false;
        }

        return GalioBCrypt.checkpw(rawPassword.toString(), encodedPassword);
    }
}
